package com.reload.controller;

import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.Duration;

/**
 * @Date: 2024/4/28 下午5:18
 * @Version: 17
 * @Author: Reloading
 * @Description:
 */
@RestController
public class HelloController {
    /**
     * WebFlux向下兼容原来的SpringMVC的大多是注解和API
     *
     * @param key
     * @return
     */
    @GetMapping("/hello")
    public String hello(@RequestParam("key") String key) {
        return "Hello World " + key;
    }

    /**
     * 推荐方式
     * 返回单个数据：Mono -- Order、User等
     * 返回多个数据：Flux -- Flux<String>
     *
     * @return
     */
    @GetMapping("/mono")
    public Mono<String> helloMono() {
        int i = 10 / 0;
        return Mono.just("哈哈");
    }

    /**
     * 配合Flux完成SSE -- Server Send Event 服务端事件推送
     *
     * @return
     */
    @GetMapping("/flux")
    public Flux<String> flux() {
        return Flux.just("你好", "我是", "Flux");
    }

    @GetMapping(value = "/sse", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> sse() {
        return Flux.range(1, 10)
                .map(i -> "ha" + i)
                .delayElements(Duration.ofMillis(500));
    }

    // SpringMVC 以前怎么用 基本可以无缝切换
    // 底层需要自己开始编写响应式代码

    /**
     * 自定义响应体
     *
     * @return
     */
    @GetMapping("/responseEntity")
    public ResponseEntity<String> responseEntity() {
        return ResponseEntity.status(200)
                .header("aaa", "bbbb")
                .contentType(MediaType.APPLICATION_JSON)
                .body("body");
    }
}